package com.example.lock.乐观锁.cas.verion_cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class CasUnSafe {

    private static final Unsafe unsafe = getUnsafe();

    private static final long valueOffset;

    private volatile int value;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                    (CasUnSafe.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    public void updateStatus(int expect, int update){
        if(unsafe.compareAndSwapInt(this,valueOffset,expect,update)){
            value = update;
            System.out.println("expect:"+expect+",update:"+update);
        }else {
            System.out.println("========失败！==========");
        }
    }

    private static Unsafe getUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) throws Exception{
        CasUnSafe unSafe = new CasUnSafe();
        for(int i = 0;i<100;i++){
            new Thread(()->{
                int expect = unSafe.value;
                int update = expect + 1;
                unSafe.updateStatus(expect,update);
            }).start();
        }

        Thread.sleep(1000);
        //System.out.println(unSafe.value);
    }
}
